import json
import crawl
import utils
from interceptor.unifty_result import unify_result
from flask import Flask
from convert import json_data_to_date_set

app = Flask(__name__)  # 创建Flask应用


# 仅获取节假日
@app.route("/date/holidays")
@unify_result
def holidays():
    year = utils.get_year()
    holidays_data = utils.holidaylist(year)
    if holidays_data is not None:
        return holidays_data
    else:
        file_data = crawl.read_file(year)
        data = []
        if file_data is not None:
            data_set = json_data_to_date_set(file_data)
            sorted_data_set = sorted(data_set, key=lambda x: x.date)
            for item in list(sorted_data_set):
                if item.holiday:
                    data.append(item.date)
        else:
            crawl_data = crawl.crawl_html_data(year)
            data_set = json_data_to_date_set(json.loads(crawl_data))
            sorted_data_set = sorted(data_set, key=lambda x: x.date)
            for item in list(sorted_data_set):
                if item.holiday:
                    data.append(item.date)
        return data


# 获取年度所有日期
@app.route("/date/annual")
@unify_result
def annual():
    year = utils.get_year()
    url = crawl.htm_url(year)
    has_records = crawl.get_record(year)
    if url is not None and not has_records:
        crawl_data = crawl.crawl_html_data(year)
        return json.loads(crawl_data)
    else:
        if url is not None and has_records:
            file_data = crawl.read_file(year)
            return file_data
        else:
            crawl_data = crawl.crawl_html_data(year)
            return json.loads(crawl_data)


# 按装订区域中的绿色按钮以运行脚本。
if __name__ == '__main__':
    app.run(port=80811)
